package cn.cdutetc.library.service.impl;

import cn.cdutetc.library.entity.dto.SystemParamConfigDTO;
import cn.cdutetc.library.entity.pojo.SystemConfig;
import cn.cdutetc.library.mapper.SystemConfigMapper;
import cn.cdutetc.library.service.SystemConfigService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统配置服务实现类
 */
@Service
public class SystemConfigServiceImpl extends ServiceImpl<SystemConfigMapper, SystemConfig> implements SystemConfigService {

    @Override
    public String getConfigValue(String configKey) {
        if (!StringUtils.hasText(configKey)) {
            return null;
        }

        LambdaQueryWrapper<SystemConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemConfig::getConfigKey, configKey);
        SystemConfig config = this.getOne(queryWrapper);

        return config != null ? config.getConfigValue() : null;
    }

    @Override
    public String getConfigValue(String configKey, String defaultValue) {
        String value = getConfigValue(configKey);
        return value != null ? value : defaultValue;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setConfigValue(String configKey, String configValue, String description) {
        if (!StringUtils.hasText(configKey)) {
            return false;
        }

        // 查询是否存在
        LambdaQueryWrapper<SystemConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemConfig::getConfigKey, configKey);
        SystemConfig config = this.getOne(queryWrapper);

        // 不存在则创建
        if (config == null) {
            config = new SystemConfig();
            config.setConfigKey(configKey);
            config.setConfigValue(configValue);
            config.setDescription(description);
            return this.save(config);
        }
        
        // 存在则更新
        config.setConfigValue(configValue);
        if (StringUtils.hasText(description)) {
            config.setDescription(description);
        }
        return this.updateById(config);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchSetConfig(Map<String, String> configMap) {
        if (configMap == null || configMap.isEmpty()) {
            return false;
        }

        for (Map.Entry<String, String> entry : configMap.entrySet()) {
            setConfigValue(entry.getKey(), entry.getValue(), null);
        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteConfig(String configKey) {
        if (!StringUtils.hasText(configKey)) {
            return false;
        }

        LambdaQueryWrapper<SystemConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemConfig::getConfigKey, configKey);
        return this.remove(queryWrapper);
    }

    @Override
    public List<SystemConfig> getAllConfigs() {
        return this.list();
    }

    @Override
    public SystemParamConfigDTO getSystemConfig() {
        SystemParamConfigDTO config = new SystemParamConfigDTO();
        
        // 系统基础信息
        config.setSystemName(getConfigValue("system_name", "图书馆管理系统"));
        config.setLibraryName(getConfigValue("library_name", "数字图书馆"));
        config.setSystemVersion(getConfigValue("system_version", "1.0.0"));
        config.setCopyright(getConfigValue("copyright", "© 2025 图书馆管理系统"));
        
        // 系统运行参数
        config.setPasswordMinLength(Integer.parseInt(getConfigValue("password_min_length", "6")));
        config.setPasswordMaxLength(Integer.parseInt(getConfigValue("password_max_length", "20")));
        config.setMaintenanceMode(Boolean.parseBoolean(getConfigValue("maintenance_mode", "false")));
        
        // 界面显示设置
        config.setThemeColor(getConfigValue("theme_color", "light"));
        
        return config;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveSystemConfig(SystemParamConfigDTO config) {
        if (config == null) {
            return false;
        }

        try {
            // 系统基础信息
            if (StringUtils.hasText(config.getSystemName())) {
                setConfigValue("system_name", config.getSystemName(), "系统名称");
            }
            if (StringUtils.hasText(config.getLibraryName())) {
                setConfigValue("library_name", config.getLibraryName(), "图书馆名称");
            }
            if (StringUtils.hasText(config.getSystemVersion())) {
                setConfigValue("system_version", config.getSystemVersion(), "系统版本");
            }
            if (StringUtils.hasText(config.getCopyright())) {
                setConfigValue("copyright", config.getCopyright(), "版权信息");
            }
            
            // 系统运行参数
            if (config.getPasswordMinLength() != null) {
                setConfigValue("password_min_length", config.getPasswordMinLength().toString(), "密码最小长度");
            }
            if (config.getPasswordMaxLength() != null) {
                setConfigValue("password_max_length", config.getPasswordMaxLength().toString(), "密码最大长度");
            }
            if (config.getMaintenanceMode() != null) {
                setConfigValue("maintenance_mode", config.getMaintenanceMode().toString(), "系统维护模式");
            }
            
            // 界面显示设置
            if (StringUtils.hasText(config.getThemeColor())) {
                setConfigValue("theme_color", config.getThemeColor(), "主题颜色");
            }
            
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean resetSystemConfig() {
        try {
            // 恢复默认配置
            Map<String, String> defaultConfigs = new HashMap<>();
            defaultConfigs.put("system_name", "图书馆管理系统");
            defaultConfigs.put("library_name", "数字图书馆");
            defaultConfigs.put("system_version", "1.0.0");
            defaultConfigs.put("copyright", "© 2025 图书馆管理系统");
            defaultConfigs.put("password_min_length", "6");
            defaultConfigs.put("password_max_length", "20");
            defaultConfigs.put("maintenance_mode", "false");
            defaultConfigs.put("theme_color", "light");
            
            return batchSetConfig(defaultConfigs);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean isMaintenanceMode() {
        String maintenanceMode = getConfigValue("maintenance_mode", "false");
        return Boolean.parseBoolean(maintenanceMode);
    }

    @Override
    public boolean verifyMaintenancePassword(String password) {
        // 硬编码的维护密码
        if ("123".equals(password)) {
            // 关闭维护模式
            return setConfigValue("maintenance_mode", "false", "系统维护模式");
        }
        return false;
    }
}